package com.buho29.rcmanager;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableDamage;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.bd.TableStatistic;


public class DamageView extends ListActivity {
    
    
    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST +1;
    private static final int EDIT_ID = Menu.FIRST + 2;
    
	private DatabaseAdapter mDbAdapter;
	private TableDamage mDbTableDamage= new TableDamage();
	
	private Long mModelId;
	private String mOrderBy = TableDamage.COL_NAME;
	private String[] mNames;
	
	private TextView mTextTotal; 

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.damage_view);
        
        Bundle extras = getIntent().getExtras();            
		if(savedInstanceState != null){
	       	mModelId = savedInstanceState.getLong(TableModel.COL_ROW_ID,0);
		}else if(extras != null){
			mModelId = extras.getLong(TableModel.COL_ROW_ID,0);
		}
        
        mDbAdapter = DatabaseAdapter.getInstance(this);
        mDbTableDamage.setSQLiteDatabase(mDbAdapter.getDatabase());
        
        TableModel m = new TableModel();
        m.setSQLiteDatabase(mDbAdapter.getDatabase());
        m.setId(mModelId);
        m.load();
        setTitle(m.getName()+">"+getText(R.string.damage));
        
        Button bt = (Button) findViewById(R.id.bt1);
        bt.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	mOrderBy = TableDamage.COL_NAME;
                populateFields();
            }
            
        });
        
        bt = (Button) findViewById(R.id.bt2);
        bt.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	mOrderBy = TableDamage.COL_CAUSE;
                populateFields();
            }
            
        });
        
        bt = (Button) findViewById(R.id.bt3);
        bt.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	mOrderBy = TableDamage.COL_PRICE;
                populateFields();
            }
            
        });
        
        bt = (Button) findViewById(R.id.bt4);
        bt.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	mOrderBy = TableDamage.COL_COUNT;
                populateFields();
            }
            
        });
        
        bt = (Button) findViewById(R.id.bt5);
        bt.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	mOrderBy = TableStatistic.COL_TOTAL;
                populateFields();
            }
            
        });
        
        mTextTotal = (TextView) findViewById(R.id.tv);
        
        populateFields();
        
        registerForContextMenu(getListView());
    }
    
    private void populateFields(){
        
    	Cursor cur= mDbTableDamage.fetchModel(mModelId, mOrderBy);
        startManagingCursor(cur);
        
        mNames = mDbTableDamage.getListNames(mModelId);
        
        setListAdapter(new DamageAdapter(this,cur));
        

		TableStatistic st = new TableStatistic();
		st.setSQLiteDatabase(mDbAdapter.getDatabase());
		
		cur = st.fechDamage(mModelId);
		startManagingCursor(cur);	
		
		float total = cur.getFloat(cur.getColumnIndexOrThrow(TableStatistic.COL_TOTAL));
		
		mTextTotal.setText(String.valueOf(round(total)));
		
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID,0, getString(R.string.New));
        return true;
    }    
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case INSERT_ID:
        	makeDiaDamage(0);
            return true;
	    }        
        return super.onMenuItemSelected(featureId, item);
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, getString(R.string.delete));
        menu.add(0, EDIT_ID, 0, getString(R.string.edit));
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch(item.getItemId()) {
	    	case DELETE_ID:
		        mDbTableDamage.setId(info.id);
		        mDbTableDamage.delete();
		        populateFields();
		        return true;
		    case EDIT_ID:
		    	mDbTableDamage.setId(info.id);
		    	mDbTableDamage.load();
		    	makeDiaDamage(info.id);
		        return true;
		}
		return super.onContextItemSelected(item);
	}
    
            
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TableModel.COL_ROW_ID, mModelId);
    }
    
    
	private void makeDiaDamage(final long id ) {
		LayoutInflater factory = LayoutInflater.from(this);
		View view = factory.inflate(R.layout.damage, null);
		
		final AutoCompleteTextView tName = (AutoCompleteTextView) view.findViewById(R.id.tvName);
		final EditText tprice = (EditText) view.findViewById(R.id.tvPrice);
		final EditText tNum = (EditText) view.findViewById(R.id.tvNum);
		final Spinner sc = (Spinner) view.findViewById(R.id.spCause);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(DamageView.this);
		builder.setIcon(R.drawable.alert_dialog_icon)
		.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	saveDamage (
            		id,
            		tName.getText().toString(),
            		Float.parseFloat(tprice.getText().toString()),
            		Integer.parseInt(tNum.getText().toString()),
            		sc.getSelectedItemPosition()
            	);
            }
         })
         .setNegativeButton(R.string.cancel, null)
         .setView(view);
		
		if(id<1){
			tName.setText("");
			Cursor cur = mDbTableDamage.fetchModel(mModelId, TableDamage.COL_NAME);
			startManagingCursor(cur);
	        
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
	                android.R.layout.simple_spinner_item, mNames);
			
			tName.setAdapter(adapter);
			
			
			tprice.setText("0");
			tNum.setText("1");
			sc.setSelection(0);
			builder.setTitle(R.string.newDamage);
		}else{
			tName.setText(mDbTableDamage.getName());
			tprice.setText(String.valueOf(mDbTableDamage.getPrice()));
			tNum.setText(String.valueOf(mDbTableDamage.getCount()));
			sc.setSelection(mDbTableDamage.getCause());
			builder.setTitle(R.string.editDamage);
		}	
        builder.create().show();
	}


	protected void saveDamage(long id ,String name, float price, int count,int cause) {
		
		if(id<1){
			mDbTableDamage.setId(0);
			mDbTableDamage.setModelId(mModelId);
		}else{
			mDbTableDamage.setId(id);
			mDbTableDamage.load();	
		}
		
		mDbTableDamage.setCount(count);
		mDbTableDamage.setPrice(price);
		mDbTableDamage.setName(name);
		mDbTableDamage.setCause(cause);
		mDbTableDamage.save();
		populateFields();
		
	}
    
    public class DamageAdapter extends BaseAdapter{
    	
        private Context mContext;
        private Cursor mCursor;
        
    	public DamageAdapter(Context c ,Cursor cursor) {
            mContext = c;
            mCursor = cursor;
		}
    	
		@Override
		public int getCount() {
			return mCursor.getCount();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			mCursor.moveToPosition(position);
            return mCursor.getLong(mCursor.getColumnIndexOrThrow(TableModel.COL_ROW_ID));
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater factory = LayoutInflater.from(mContext);
			View view = factory.inflate(R.layout.row_damage, null);
			
			TextView tv1 = (TextView) view.findViewById(R.id.tv1);
			TextView tv2 = (TextView) view.findViewById(R.id.tv2);
			TextView tv3 = (TextView) view.findViewById(R.id.tv3);
			TextView tv4 = (TextView) view.findViewById(R.id.tv4);
			TextView tv5 = (TextView) view.findViewById(R.id.tv5);
			
			
			mCursor.moveToPosition(position);
			
			tv1.setText(
				mCursor.getString(mCursor.getColumnIndexOrThrow(TableDamage.COL_NAME))
			);
			
			int id = mCursor.getInt(mCursor.getColumnIndexOrThrow(TableDamage.COL_CAUSE));
			if(id==0){
				tv2.setText("usury");
			}else{
				tv2.setText("accident");
			}
			
			float price =  mCursor.getFloat(mCursor.getColumnIndexOrThrow(TableDamage.COL_PRICE));
			int count = mCursor.getInt(mCursor.getColumnIndexOrThrow(TableDamage.COL_COUNT));
			float total = mCursor.getFloat(mCursor.getColumnIndexOrThrow(TableStatistic.COL_TOTAL));
			
			tv3.setText(String.valueOf(round(price)));
			tv4.setText(String.valueOf(count));
			tv5.setText(String.valueOf(round(total)));	
						
			return view;
		}
		
    	
    }
	private static float round(float f){
		return f;//Math.round(f*10)/10;
	}
}